package dao

import (
	"context"
	"sale-admin/internal/dal"

	"github.com/golang-module/carbon/v2"
	"gorm.io/gorm"
)

type Event struct{}

type SalesIDEventList struct {
	SalesID          string  `json:"sales_id"`
	RobotName        string  `json:"robot_name"`
	EventCount       int64   `json:"event_count"`
	AffectedTimeMill float64 `json:"affected_time_mill"`
	MoveCount        int64   `gorm:"-" json:"move_count"`
	EmergencyCount   int64   `gorm:"-" json:"emergency_count"`
}

func (Event) GetEventList(ctx context.Context, db *gorm.DB, startTime, endTime string) (data []SalesIDEventList, err error) {
	m := dal.Use(db).MaEvent
	tx := m.WithContext(ctx)
	if startTime != "" && endTime != "" {
		start := carbon.ParseByLayout(startTime, carbon.DateTimeLayout).ToStdTime()
		end := carbon.ParseByLayout(endTime, carbon.DateTimeLayout).ToStdTime()
		tx = tx.Where(m.AddTime.Between(start, end))
	}
	tx.Select(
		m.SalesID,
		m.RobotName,
		m.ID.Count().As("event_count"),
		m.AffectedTimeMill.Sum().As(m.AffectedTimeMill.ColumnName().String()),
	).
		Group(m.RobotName).
		Order(m.RobotName).
		Scan(&data)
	for k, v := range data {
		tx1 := m.WithContext(ctx).
			Where(m.RobotName.Eq(v.RobotName))
		if startTime != "" && endTime != "" {
			start := carbon.ParseByLayout(startTime, carbon.DateTimeLayout).ToStdTime()
			end := carbon.ParseByLayout(endTime, carbon.DateTimeLayout).ToStdTime()
			tx1 = tx1.Where(m.AddTime.Between(start, end))
		}
		tx2 := tx1.WithContext(ctx)
		data[k].MoveCount, _ = tx2.Where(m.Move.Eq(1)).Count()
		data[k].EmergencyCount, _ = tx2.Where(m.Emergency.Eq(1)).Count()
	}
	return
}
